package com.py.credit.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.PromiseBookApprovalEnum;
import com.py.credit.entity.enums.PromiseBookReportEnum;
import com.py.credit.entity.enums.PromiseBookStatisticsEnum;
import com.py.credit.entity.enums.PromiseBooksByZtEnum;
import com.py.credit.service.PromiseBookStatisticsService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.XylyStatisticsService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/xylyStatistics")
public class XylyStatisticsController {
	
	private final static String FRONT_TABLE_ID = "promiseBookStatistics";
	

	@Autowired
	private XylyStatisticsService xylyStatisticsService;

    @Autowired
    private RemoteBaseService remoteBaseService;
    
    @Value("${absolutepath}")
    private String absolutepath;
    
    
    /**
     * 统计页面 ：  高级检索  只统计审批成功的
     * @param type   承诺书类型:主动承诺和行业自律型承诺（ZD）、审批替代型承诺（SP）、容缺受理型承诺（RQ）、失信修复型承诺（SX）',
     * @param ztType 主体类型
     * @param deptId 部门id
     * @param condition
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/getAllPromiseBooks.json")
    public RestServiceResult<List<Map<String, Object>>> getAllPromiseBooks(
    		@RequestParam(value = "type", required = false,defaultValue = "") String type,
    		@RequestParam(value = "ztType",required = false,defaultValue = "") String ztType,
    		@RequestParam(value = "deptId",required = false,defaultValue = "") Long deptId,
    		@RequestParam(value = "condition", defaultValue = "", required = false) String condition ,
    		Page page , HttpServletRequest request) {

    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookStatisticsController#getAllPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookStatisticsController#getAllPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
        
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? PromiseBookApprovalEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        String[] additionalColumns = {"id", "path", "tybm", "deptId", "isDel","reportUserId","areaId","parentId","batchId","areaName","topDeptId"};

        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        try {
        	List<Map<String, Object>> list = xylyStatisticsService.getPromiseBooksByConditionForPage(type,ztType,deptId,
        		showColumns,additionalColumns, condition, page);
        	
        	result.setData(list);
        	result.setCount(page.getTotalCount());
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookStatisticsController#getAllPromiseBooks", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;

    }
    
    @RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("PromiseBookStatisticsController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}

			String column = StringUtils.join(columns, ",");

			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}
    
   
    /**
     * 左侧部门统计
     * @param 统计类型：1，顶层部门(dept_id)；2，主体类型(zt_type)；3，承诺书类型(type)；
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/getStatisticsByDept.json")
    public RestServiceResult<List<Map<String, Object>>> getStatisticsByDept(
    		@RequestParam(value = "type", required = false,defaultValue = "") String type,
    		@RequestParam(value = "ztType",required = false,defaultValue = "") String ztType,
    		@RequestParam(value = "deptId",required = false,defaultValue = "") Long topDeptId,
    		HttpServletRequest request) {

    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        try {
        	List<Map<String, Object>> list = xylyStatisticsService.getStatistics(type,ztType,topDeptId);
        	
        	result.setData(list);
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;
    }
    
    /**
     * 右侧统计
     * @param 统计类型：1，顶层部门(dept_id)；2，主体类型(zt_type)；3，承诺书类型(type)；
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/getStatisticsByDeptMore.json")
    public RestServiceResult<List<Map<String, Object>>> getStatisticsByDeptMore(
    		Page page , HttpServletRequest request) {

    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        try {
        	List<Map<String, Object>> list = xylyStatisticsService.getStatisticsForPage(page);
        	
        	result.setData(list);
        	result.setCount(page.getTotalCount());
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;
    }
    
    

    //表头展示列
    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
        return new RestServiceResult<>(PromiseBookStatisticsEnum.getOptionalColumns());
    }
    
    // 高级查询自定义列表选项
    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
        return new RestServiceResult<>(PromiseBookStatisticsEnum.getAdvancedConditionColumns());
    }
    
    /**
     * 
     * @param type
     * @param ztType
     * @param deptId
     * @param condition
     * @param columnEN
     * @param page
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/export.json")
    public void export(
    		@RequestParam(value = "type", required = false,defaultValue = "") String type,
    		@RequestParam(value = "ztType",required = false,defaultValue = "") String ztType,
    		@RequestParam(value = "deptId",required = false,defaultValue = "") Long deptId,
            @RequestParam(value = "condition", defaultValue = "", required = false) String condition,
            @RequestParam(value = "columnEN", defaultValue = "", required = false) String columnEN,
            Page page,HttpServletResponse response,HttpServletRequest request) throws IOException {
    	
    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo) {
	            ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
	            throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
    	
        page.setLimit(1000);
        List<String> columns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> data = xylyStatisticsService.getPromiseBooksByConditionForPage(type, ztType,deptId , 
        		columns, null, condition,page);
        List<OptionalColumn> optionalColumns = PromiseBookReportEnum.getOptionalColumns();
        ExcelUtil.downloadExcel(response, data, "上传承诺书记录", "上传承诺书记录", columns, optionalColumns);
    }
   
    
    
    /**
     * 一站式查詢高級搜索
     * @param ztName
     * @param condition
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/promiseBooksByZt.json")
    public RestServiceResult<List<Map<String, Object>>> promiseBooksByZt(
    		@RequestParam(value = "ztName",required = false,defaultValue = "") String ztName,
    		@RequestParam(value = "condition", defaultValue = "", required = false) String condition ,
    		Page page , HttpServletRequest request) {
    	
    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookApprovalController#getPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookApprovalController#getPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        List<String> showColumns = PromiseBooksByZtEnum.getDefaultShowColumnEN();
        String[] additionalColumns = {"id", "path", "tybm", "deptId", "isDel","reportUserId","areaId","parentId","batchId","areaName"};
        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        try {
        	List<Map<String, Object>> list = xylyStatisticsService.promiseBooksByZtForPage(ztName,showColumns,additionalColumns, condition, page);
        	
        	result.setData(list);
        	result.setCount(page.getTotalCount());
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookApprovalController#getPromiseBooks", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;

    }
    
    //表头展示列
    @RequestMapping(value = "/getOptionals.json")
    public RestServiceResult<List<OptionalColumn>> getOptionals() {
        return new RestServiceResult<>(PromiseBooksByZtEnum.getOptionalColumns());
    }
    
    // 高级查询自定义列表选项
    @RequestMapping(value = "/getAdvancedConditions.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditions() {
        return new RestServiceResult<>(PromiseBooksByZtEnum.getAdvancedConditionColumns());
    }
    
    
    /**
     * 获取所有顶层部门
     * @return
     */
    @RequestMapping(value = "/getAllTopDepts.json")
    public RestServiceResult<List<Map<String, Object>>> getAllTopDepts() {

        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        try {
        	List<Map<String, Object>> list = xylyStatisticsService.getAllTopDepts();
        	
        	result.setData(list);
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookReportController#getAllTopDepts", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;
    } 
    
    
    
    /**
     * 右侧承诺书类型统计
     * @param 统计类型
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/getStatisticsByType.json")
    public RestServiceResult<List<Map<String, Object>>> getStatisticsByType(
    		@RequestParam(value = "type", required = false,defaultValue = "") String type,
    		@RequestParam(value = "ztType",required = false,defaultValue = "") String ztType,
    		@RequestParam(value = "deptId",required = false,defaultValue = "") Long topDeptId,
    		HttpServletRequest request) {

    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        String[] typeArr = new String[] {"DL","GC","GQ","GG","ZF"};
        
        try {
        	List<Map<String, Object>> list  = new ArrayList<Map<String,Object>>();
        	String tablename = "";
        	for(String s : typeArr) {
        		if("DL".equals(s)) {
        			tablename = "t_1000000010404_pezc5o18VN";	
        		}else if("GC".equals(s)) {
        			tablename = "t_1000000010402_qAcqVkiVSN";	
        		}else if("GQ".equals(s)) {
        			tablename = "t_1000000010400_h65MpMNqWZ";	
        		}else if("GG".equals(s)) {
        			tablename = "t_1000000010399_aUDgU4MoxP";	
        		}else if("ZF".equals(s)) {
        			tablename = "t_1000000010398_7BQJb5pmyp";	
        		}
        		Map<String, Object> map = 	xylyStatisticsService.getStatisticsByType(s,tablename);
        		list.add(map);
        	}
        
        	
        	Label : for(int i = 0 ; i < typeArr.length ; i++) {
        		for(Map<String , Object> map : list) {
        			String typeEn = (String)map.get("type");
            		if(typeArr[i].equals(typeEn)) {
            			map.put("typeName",getTypeName(typeEn));
            			continue Label;
            		}
            	}
//        		if(StringUtils.isEmpty(type)) {
//        			Map<String, Object> newMap = new HashMap<>();
//            		newMap.put("typeName",getTypeName(typeArr[i]));
//            		newMap.put("count", 0);
//            		list.add(newMap);
//        		}
    		}
        	
        	
        	result.setData(list);
        	result.setCode(RestServiceResult.CODE_SUCCESS);
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;
    }
    
    /**
     * 类型匹配中文名
     * @param type
     * @return
     */
    private String getTypeName(String type) {
    	switch (type) {
			case "DL":
				return "电力中长期交易合同";
			case "GC":
				return "工程建设合同";
			case "GQ":
				return "国企采购";
			case "GG":
				return "公共资源交易";
			case "ZF":
				return "政府采购";
			default:
				return null;
		}
    } 
    
    
    

    @RequestMapping(value = "/exportMore.json")
    public RestServiceResult<List<Map<String, Object>>> exportMore(Page page,HttpServletRequest request, HttpServletResponse response) {

    	RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
                throw new ServiceException("未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
            throw new ServiceException("未获取到当前用户信息！");
        }
        
        
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        
        try {
        	List<Map<String, Object>> list = xylyStatisticsService.getStatisticsForPage(page);
        	
        	// 创建HSSFWorkbook对象(excel的文档对象)
    		HSSFWorkbook wb = new HSSFWorkbook();
    		// 建立新的sheet对象（excel的表单）
    		HSSFSheet sheet = wb.createSheet("部门承诺书统计");	
    		
    		sheet.setColumnWidth(0, 10000);
    		sheet.setColumnWidth(1, 5000);
    		// 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
    		HSSFRow row1 = sheet.createRow(0);
    		// 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
    		HSSFCell cell = row1.createCell(0);
    		// 设置单元格内容
    		cell.setCellValue("部门承诺书统计列表详情");
    		// 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
    		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
    		// 在sheet里创建第二行
    		HSSFRow row2 = sheet.createRow(1);
    		// 创建单元格并设置单元格内容
    		row2.createCell(0).setCellValue("部门名称");
    		row2.createCell(1).setCellValue("审批通过数量");
    		
    		for (int i = 0; i < list.size(); i++) {

    			String cellFirst = (String)(list.get(i).get("report_dept"));

    			HSSFRow row3 = sheet.createRow(2 + i);
    			row3.createCell(0).setCellValue(cellFirst);
    			row3.createCell(1).setCellValue(String.valueOf(list.get(i).get("count")));
    		}

    		// 输出Excel文件
    		OutputStream output = response.getOutputStream();
    		response.reset();

    		String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
    		String headStr = "attachment; filename=\"" + fileName + "\"";

    		response.setHeader("Content-disposition", headStr);
    		response.setContentType("application/msexcel");
    		wb.write(output);
    		output.close();
    		return null;
        	
        }catch (Exception e) {
        	ExceptionLogger.error("PromiseBookReportController#exportMore", "系统异常，请联系管理员！");
        	
        	result.setCode(RestServiceResult.CODE_UNKNOW);
        	result.setMsg("系统异常，请联系管理员！");
		}
        
        return result;
    }
    
}
